﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using System.Data;
using System.Collections;

public partial class AddProduct : System.Web.UI.Page
{
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ViewState.Add("myitems", new Dictionary<string,string>());
            ViewState.Add("olditems", new Dictionary<string, string>());
           
            //DB.DELETE("company_product", "int,company_id," + Session["company_id"].ToString());  
           adjustclient(int.Parse( Session["company_id"].ToString()));
        }
        else
        {
            Dictionary<string, string> myitems = (Dictionary<string, string>)ViewState["myitems"];
           
            if (myitems.Count > 0)
            {
                ClearImageList();
               
                foreach (KeyValuePair<string, string> k in myitems)
                {

                    createImageListItem(k.Value.Split('~')[0], k.Key, k.Value.Split('~')[1]);

                }


            }
            //editgrid();

        }
    }
    public void adjustclient(Int64 id)
    {
        Dictionary<string, string> databaseitems = new Dictionary<string, string>();
        string select = "select p.product,p.id,p.puplisher_id from  products p INNER JOIN company_product t ON t.product_id = p.id WHERE t.company_id= " + id;
        DataSet ds = DB.getdata(select);
        //////////////adjust main info//////////////////////////
        string myids = "";
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            databaseitems.Add(dr["id"].ToString(), dr["product"].ToString() + "~" + dr["puplisher_id"].ToString());
           // old.Add(dr["id"].ToString(), dr["product"].ToString() + "," + dr["puplisher_id"].ToString());

            myids += dr["id"].ToString() + ",";
            createImageListItem(dr["product"].ToString(), dr["id"].ToString(), dr["puplisher_id"].ToString());
        
        }

        if (myids != "")
        {
            myids = myids.Trim(",".ToCharArray()[0]);
            SqlDataSource1.SelectCommand = "select p.*,t.product_type from  products p INNER JOIN product_types t ON t.id = p.product_type_id WHERE p.id not in(" + myids + ")";
        }
       
        ViewState["olditems"]= databaseitems;
        ViewState["myitems"] = databaseitems; //ibrahim code
            GridView1.DataBind();

    }
    protected void DivClick(object sender, EventArgs e)
    {
        Dictionary<string, string> myitems = (Dictionary<string, string>)ViewState["myitems"];
        string bb = ((HiddenField)((System.Web.UI.HtmlControls.HtmlGenericControl)sender).FindControl("myvalue")).Value;

        ImageListItem dd = (ImageListItem)ListT.FindControl(bb);
        
        ListT.Controls.Remove(dd);
        ListT.DataBind();
        myitems.Remove(bb);
        editgrid();
        ViewState["myitems"] =myitems;

    }

    protected void ClearImageList()
    {
        for (int i = 0;  i < ListT.Controls.Count;i++)
        {
            if (ListT.Controls[i] is ImageListItem)
            {
                ListT.Controls.Remove(ListT.Controls[i]);
            }
        }
        
    }
    protected void createImageListItem(string text, string value,string data)
    {
        //ibrahim code 
        foreach(Control ctl in ListT.Controls)
        {
            if (ctl is ImageListItem)
            {
                ImageListItem imagelistitem = (ImageListItem)ctl;
                if (imagelistitem.Values == value)
                {
                    throw new Exception("Items is already exist in the ImageList");
                }
            }
        }
        //ibrahim code
        ImageListItem myUserControl = (ImageListItem)Page.LoadControl("~/ImageListItem.ascx");
        myUserControl.DisplayText = text;
        myUserControl.Values = value;
        myUserControl.Data = data;
        myUserControl.DivClick += new EventHandler(DivClick);
        myUserControl.ID = value;


        ListT.Controls.Add(myUserControl);

    }

    //http://www.facebook.com/hussien.elaraby1
    //   //fb.me/9UWGUK4vxs650W

    protected override void InitializeCulture()
    {
        if (Session["CurrentCulture"] != null)
        {
            string lang = Session["CurrentCulture"].ToString();
            if (lang != null && lang != "")
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
                Thread.CurrentThread.CurrentCulture.DateTimeFormat = new CultureInfo("en-US", false).DateTimeFormat;
                // Thread.CurrentThread.CurrentCulture.Calendar=new  System.Globalization.GregorianCalendar();

            }
        }

    }
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
      
        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    e.Row.Attributes.Add("onmouseover", "this.Mystyle=this.style.backgroundColor;this.style.backgroundColor='#FFFFA8'");

        //    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.Mystyle");
        //}
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {

    }
    protected void searchfield_TextChanged(object sender, EventArgs e)
    {
        SqlDataSource1.SelectCommand = "select p.*,t.product_type from  products p INNER JOIN product_types t ON t.id = p.product_type_id WHERE product  LIKE '" + searchfield.Text + "%'";
        GridView1.DataBind();
   
    }
    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chk=(CheckBox)sender;
        int dd =((GridViewRow) chk.NamingContainer).RowIndex;
        string[]sts=chk.ToolTip.Split('~');
        createImageListItem(sts[1], sts[0], sts[2]);
        Dictionary<string, string> myitems = (Dictionary<string, string>)ViewState["myitems"];
        myitems.Add(sts[0], sts[1] + "~" + sts[2]);
        ViewState["myitems"] = myitems;
        editgrid();

        
        
    }
    public void editgrid()
    {
        Dictionary<string, string> myitems = (Dictionary<string, string>)ViewState["myitems"];
        if (myitems.Count > 0)
        {
            string myids = "";
            foreach (KeyValuePair<string, string> k in myitems)
            {
                myids += k.Key + ",";
            }
            myids = myids.Trim(",".ToCharArray()[0]);
            SqlDataSource1.SelectCommand = "select p.*,t.product_type from  products p INNER JOIN product_types t ON t.id = p.product_type_id WHERE p.id not in(" + myids + ")";
            GridView1.DataBind();
        }
    
    }
    protected void save_Click(object sender, EventArgs e)
    {
        Dictionary<string,string>olditems  = (Dictionary<string, string>)ViewState["olditems"];
        Dictionary<string, string> myitems = (Dictionary<string, string>)ViewState["myitems"];

      //  DB.DELETE("company_product", "int,company_id," + Session["company_id"].ToString());
        List<string> fields = new List<string>();
        ArrayList values = new ArrayList();
        List<string> types = new List<string>();
        ///////////////

        // deleting keys that doesnot exist in myitems list 
        foreach (var key in olditems)
        {
            if (!myitems.ContainsKey(key.Key))
            {
                DB.DELETE("company_product", "int,product_id," + key.Key);
                DB.DELETE("daily_checking", "int,company_product_id," + key.Key);
                DB.DELETE("internal_copies", "int,company_product_id," +key.Key);
                DB.DELETE("internal_checking", "int,company_product_id," + key.Key);
            }
        }
        // Inserting new keys that doesnot exist in olditems list 
        foreach(var key in myitems)
        {
          if(!olditems.ContainsKey(key.Key))
          {
                    fields.Clear();
                    types.Clear();
                    values.Clear();
                    //////////////////
                    fields.Add("company_id");
                    types.Add("int");
                    values.Add(int.Parse(Session["company_id"].ToString()));
                    ///////////////////////

                    fields.Add("distributer_id");
                    types.Add("int");
                    values.Add(0);
                    ///////////////////////
                    ///////////////////////

                    fields.Add("publisher_id");
                    types.Add("int");
                    values.Add(key.Value.Split('~')[1]);
                    ///////////////////////
                    fields.Add("product_id");
                    types.Add("int");
                    values.Add(key.Key);
                    /////////////////////////////
                    fields.Add("company_product_id");
                    types.Add("int");
                    values.Add(0);
                    /////////////////////////////
                    fields.Add("startdate");
                    types.Add("datetime");
                    values.Add(DateTime.Now.ToShortDateString());
                    /////////////////////////////
                    fields.Add("enddate");
                    types.Add("datetime");
                    values.Add(DateTime.Now.ToShortDateString());
                    /////////////////////////////
                    int ff = (int)DB.INSERT("company_product", fields, types, values);
          }
        }
        Page.ClientScript.RegisterStartupScript(this.GetType(), "reports", "alert('تم التسجيل بنجاج');", true);
        ViewState["olditems"]= ViewState["myitems"];

        //if (ListT.Controls.Count > 1)
        //{
        //    for (int i = 1; i < ListT.Controls.Count; i++)
        //    {
        //        ImageListItem dd = (ImageListItem)ListT.Controls[i];
        //        //////////
        //        if (myitems.ContainsKey(dd.Values))
        //        {

        //            myitems.Remove(dd.Values);
        //        }
        //        else
        //        {


        //            fields.Clear();
        //            types.Clear();
        //            values.Clear();
        //            //////////////////
        //            fields.Add("company_id");
        //            types.Add("int");
        //            values.Add(int.Parse(Session["company_id"].ToString()));
        //            ///////////////////////

        //            fields.Add("distributer_id");
        //            types.Add("int");
        //            values.Add(0);
        //            ///////////////////////
        //            ///////////////////////

        //            fields.Add("publisher_id");
        //            types.Add("int");
        //            values.Add(dd.Data);
        //            ///////////////////////
        //            fields.Add("product_id");
        //            types.Add("int");
        //            values.Add(int.Parse(dd.Values));
        //            /////////////////////////////
        //            fields.Add("company_product_id");
        //            types.Add("int");
        //            values.Add(0);
        //            /////////////////////////////
        //            fields.Add("startdate");
        //            types.Add("datetime");
        //            values.Add(DateTime.Now.ToShortDateString());
        //            /////////////////////////////
        //            fields.Add("enddate");
        //            types.Add("datetime");
        //            values.Add(DateTime.Now.ToShortDateString());
        //            /////////////////////////////
        //            int ff = (int)DB.INSERT("company_product", fields, types, values);
        //        }
                   
        //    }

        //    if (d.Count > 0)
        //    {
        //        foreach (KeyValuePair<string, string> k in d)
        //        {
        //            DB.DELETE("company_product", "int,product_id," + k.Key);
        //            DB.DELETE("daily_checking", "int,company_product_id," + k.Key);
        //            DB.DELETE("internal_copies", "int,company_product_id," + k.Key);
        //            DB.DELETE("internal_checking", "int,company_product_id," + k.Key);

        //        }
            
            
        //    }
        //    Page.ClientScript.RegisterStartupScript(this.GetType(), "reports", "alert('تم التسجيل بنجاج');", true);
        //    Response.Redirect("~/companypart/AddProduct.aspx");
        //}
        ////////////////////////////////////////////////////////

    }



    protected void ImageButton1_Click(object sender, EventArgs e)
    {
       
    }
    public void search()
    {

        if (searchfield.Text.Length != 0)
        {


            Label1.Text = "";

            DataSet ds;

            string loadsearch = DB.remove_spaces(searchfield.Text);

            if (DropDownList1.SelectedValue == "0")
            {
                ds = DB.quick_search("products", loadsearch);
            }
            else
            {
                ds = DB.quick_search("products", loadsearch, DropDownList1.SelectedValue);
            }


            if (ds.Tables[0].Rows.Count > 0)
            {


                GridView1.DataSource = ds.Tables[0];
                GridView1.DataBind();
                Label1.Visible = false;

            }
            else
            {

                Label1.Visible = true;

            }


        }
        else
        {

            Label1.Text = " من فضلك لا يجوز ترك هذا الحقل خاليا";
            Label1.Visible = true;
        }


    }
}
